<?php
class Cache{
	
    //静态缓存文件后缀名
    const EXT = 'txt';
	const _LOG = 'log';
	
    //定义缓存文件存放路径
    private $_dir;
	public $cache_api='';
	public $cache_time='';

    public function __construct($cache_name='',$cache_time=300){
        $this->_dir = $_SERVER['DOCUMENT_ROOT'].'/Mapi/cache/';
		if($cache_name!=''){
			$this->cache_api = $cache_name;
			$this->cache_time = $cache_time;
		}
    }


	public function check_cache($cache_time=300){

		$file_name = $this->_dir.$this->cache_api.'.'.self::_LOG;
		
	    //读取缓存
        if(!is_file($file_name)){
			
            return false;

        }else{
			
			$con = json_decode(file_get_contents($file_name),true);

			$period= time()-intval($con['filetime']);
	
			if($period> $cache_time){
				return false;
			}

            return true;
        }
	 }

	
    public function cacheData($v = '',$path = ''){
        //文件名
		$bag_name = $this->_dir.$path.$this->cache_api;

        $data_name = $bag_name.'.'.self::EXT;
		$file_name = $bag_name.'.'.self::_LOG;

        //$v不为‘’：存储缓存或者删除缓存
        if($v !== ''){

            //删除缓存
			$this->del_cache($data_name);
			$this->del_cache($file_name);

            //存储缓存
            $dir = dirname($data_name);
            if(!is_dir($dir)){
                mkdir($dir,0777);
            }
			$dir = dirname($file_name);
            if(!is_dir($dir)){
                mkdir($dir,0777);
            }
            //把$v转成string类型
            $_return = array(
                'filename' => $file_name,
                'filetime' => time() //文件创建(修改)时间
            );
			file_put_contents($file_name,json_encode($_return));

			$data = $this->outPut($v);
            return file_put_contents($data_name,$data);
        }


    }


	public function read_cache(){

		 $file_name = $this->_dir.$this->cache_api.'.'.self::EXT;
	    //读取缓存
        if(!is_file($file_name)){
            return false;
        }else{
            return file_get_contents($file_name);
        }
	 }

	public function outPut($data, $pager = NULL)
    {
		if (isset($data['data'])) {
		    $data = $data['data'];
		}
        $data = array_merge(array('data'=>$data), array('status' => array('succeed' => 1)));
		if (!empty($pager)) {
			$data = array_merge($data, array('paginated'=>$pager));
		}
        return json_encode($data);
    }
	
	public function del_cache($filename){
        //文件名
		if(file_exists($filename)){
		 @unlink($filename);
		}
        
	}
           
}